﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CheckSum
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// SEMI M13-0998  CheckSum
        /// </summary>
        const int len = 18;
        long[] A_Coefficient = new long[len];
        long[] InputStr = new long[len];
        public MainWindow()
        {
            InitializeComponent();

            //初始化系数
            for (int i = 0; i < len; i++)
            {
                A_Coefficient[i] = (long)Math.Pow(8, len-1 - i);
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

            string xx = textBox1.Text.Trim();

            if (xx.Length == len)
            {
                //计算总和
                long sum = 0;
                for (int i = 0; i < len; i++)
                {
                    InputStr[i] =(System.Text.Encoding.ASCII.GetBytes(xx.Substring(i,1))[0]-32);
                    sum += InputStr[i] * A_Coefficient[i];
                }
                //mode 59
                long mod59 = sum % 59;

                

                if (mod59 != 0)
                {
                    //59-mode
                    int _59_mod = 59 - (int)mod59;
                  

                    //转化为6位二进制
                    string _6 = System.Convert.ToString(_59_mod, 2).PadLeft(6, '0');

                    //字符串转化为数字
                    int pre3 = System.Convert.ToInt32(_6.Substring(0, 3), 2);
                    int last3 = System.Convert.ToInt32(_6.Substring(3, 3), 2);

                    byte[] array = new byte[1];
                    array[0] = (byte)(Convert.ToInt32(InputStr[len-1] + last3 + 32)); //ASCII码强制转换二进制
                    string add32_last3_ASCII = System.Text.Encoding.ASCII.GetString(array);

                    array[0] = (byte)(Convert.ToInt32(InputStr[len-2] + pre3 + 32)); //ASCII码强制转换二进制
                    string add32_pre3_ASCII = System.Text.Encoding.ASCII.GetString(array);

                    textBlock1.Text = add32_pre3_ASCII + add32_last3_ASCII;
                }
                else
                {

                    //取二进制
                    textBlock1.Text = mod59.ToString();
                }
              
            }
        }
    }
}
